{extend name="layout/app" /}

{block name="title"}发长文{/block}

{block name="css"}
<link rel="stylesheet" href="/static/lake/lake.min.css">
{/block}

{block name="main"}
<main role="main" class="d-flex flex-grow-1">
    <div class="d-flex main-wrap justify-content-between min-vh-100">
        <div class="primary-col d-flex flex-column vh-100">
            <!-- 顶部导航条 -->
            <div class="breadcrumb d-flex justify-content-between align-items-center px-3 js-scroll">
                <a href="/login" class="btn btn-sm btn-icon only-on-sm" role="button">
                    <i class="iconfont icon-user"></i>
                </a>
                <h2 class="fs-18px fw-bold cursor-pointer js-top">发长文</h2>
                <button type="button" id="submitBtn" class="btn btn-sm btn-primary" title="发布">发布</button>
            </div>
            <form id="create-blog" method="post" action="/blog/submit">
                <input type="hidden" id="csrf_token" name="csrf_token" value="{:csrf_token()}">
                <div id="editor-wrapper">
                    <div id="toolbar-container" class="border-top border-bottom"></div>
                    <input type="text" id="title" name="title"
                        class="form-control rounded-0 border-0 p-3 pb-1 fw-bold fs-4" placeholder="输入标题..."
                        spellcheck="false" maxlength="128" required>
                    <div id="editor-container" placeholder="中华人民共和国"></div>
                </div>
                <button type="submit" class="btn btn-sm btn-primary" title="发布">发布</button>
            </form>
        </div>
        <div class="sidebar-col">
            <div class="position-sticky sidebar-sticky">
                <div class="position-relative mt-2 mb-3">
                    <i class="iconfont icon-search search-iconfont"></i>
                    <input class="form-control rounded-5 search-input" type="text" placeholder="搜索">
                </div>
                <div class="tile mb-3">
                    <h2 class="mb-0 py-12px px-3 fs-6 fw-bold">每日帖不过３😉</h2>
                    <div class="px-3 pb-3">
                        <p class="mt-1 mb-3 fs-15px">友情提示，发帖和回帖都需要<i class="squiggle">扣除１枚金币</i>。</p>
                        <a class="btn btn-dark rounded-pill" href="/reward">领取今日登录奖励</a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</main>
{/block}

{block name="js"}
<script src="/static/lake/lake.min.js"></script>
<script>
    document.addEventListener("DOMContentLoaded", () => {
        // 当前链接添加 active
        highlightActiveLink("home");
        // 切换当前链接的 iconfont
        updateIconClassOnActive('.app-link', 'icon-home', 'icon-home-fill');
        // 选中标题框
        document.getElementById('title').focus();

        // 编辑器
        const { Editor, Toolbar } = Lake;

        const toolbar = new Toolbar({
            root: '#toolbar-container',
            items: [
                'bold', 'numberedList', 'bulletedList', 'checklist', 'link',
                'image', 'code', 'codeBlock', 'table', 'blockQuote', 'removeFormat',
            ],
        });
        const editor = new Editor({
            root: '#editor-container',
            value: '<p><br></p>',
            placeholder: '输入正文...',
            lang: 'zh-CN',
            toolbar,
        });

        editor.render();

        // 增强的表单验证
        const validateForm = () => {
            const title = document.getElementById('title').value.trim();
            const content = editor.getValue();

            if (content === '<p><br></p>') {
                content = '';
            }

            if (!title) {
                toast('标题不能为空');
                return false;
            }
            if (title.length > 80) {
                toast('标题长度超过限制');
                return false;
            }
            if (!content) {
                toast('正文内容不能为空');
                return false;
            }
            return true;
        };

        // 使用事件委托防止动态加载问题
        document.getElementById('submitBtn').addEventListener('click', async (e) => {
            e.preventDefault()

            if (!validateForm()) return;

            // 使用Fetch API提交
            try {
                // 使用FormData支持文件上传（如果需要）
                const formData = new FormData();
                formData.append('csrf_token', document.getElementById('csrf_token').value);
                formData.append('title', document.getElementById('title').value.trim());
                formData.append('content', editor.getValue());

                const response = await fetch('/blog/submit', {
                    method: 'POST',
                    body: formData  // 自动设置Content-Type为multipart/form-data
                });

                const result = await response.json();

                if (response.ok) {
                    toast('发布成功');
                    setTimeout(() => {
                        window.location.href = `/blog/${result.id}`; // 假设返回文章ID
                    }, 1500);
                } else {
                    toast(result.message || '提交失败');
                }
            } catch (error) {
                // console.error('提交错误:', error);
                toast('网络异常，请稍后重试');
            }
        });
    });
</script>
{/block}